<template>
  <div class="work-tree-data-box product-menu-new">

    <div class="product-menu-new-title">
      <div class="product-menu-new-title-left">
        {{ titleText }}
      </div>
      
      <div class="flex-x">
        <FormCellChange
          class="mar-r-8"
          :count="formCellCount"
          @update="
            e => {
              formCellCount = e;
            }
          "
        ></FormCellChange>
        <el-button type="plain-third" v-if="id" @click="back">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="plain-third" @click="showMoreFieldsDialog">
          {{ $t('product.productType.btns.btn9') }}
        </el-button>
        <el-button type="plain-third" @click="showDialog('copy')">
          {{ $t('product.productType.btns.btn10') }}
        </el-button>
        <el-button type="primary" :loading="pending" @click="submitWithEditAndQuality">{{ $t('common.base.save') }}</el-button>
      </div>
    </div>

    <div class="product-menu-new-content" :class="[formCellCount > 1 ? 'bbx-normal-form-builder-cell' : '']">
    <form-builder ref="form"
      class="bbx-cell-form-builder"
      :formStatus="id ? 'edit' : 'new'"
      :fields="fields"
      :value="productMenuValue"
      mode="product_menu"
      :extraValidations="extraValidations"
      :form-cell-count="formCellCount"
      @update="update">
      <template slot="parentIds" slot-scope="{ field }">
        <form-item :label='field.displayName' class="add-product-item bbx-form-cell-item">
          <form-cascader :field='field' popper-class='cascader-all' :props-v2='casProps' :tree='directoryTree' version='new' :show-all-levels='true' :value='parentIds' @input='catalogInput'></form-cascader>
          <el-button class="directory-btn" type="plain-third" @click="createDirectory">{{ $t('common.base.create') }}</el-button>
        </form-item>
      </template>
      <!-- 对于这类额外配置的表单项，不方便套用原先的校验逻辑，目前加了单独的校验方式，
      后期对表单项内容有改动的话，建议改造为符合原先的校验方式~ -->
      <template slot="product_menu_part" slot-scope="{ field }">
        <div class="product_menu_box product_menu_first bbx-form-item">
          <div class="normal-title-2 ">
            <div class="flex-1" :class="{
              'form_is_required': !field.isNull
            }">{{ $t('product.productType.type.productMenuPart') }}</div>
            <el-button @click="showDialog('part')" class="btn_primary">{{ $t('common.base.add2') }}</el-button>
          </div>

          <mini-table 
            :id="id"
            v-if="id && !clone"
            ref="partTable"
            data-type="part"
            @hasValue="hasValue => hasValueChange('product_menu_part', hasValue)"
            page-type="edit" />
          <create-mini-table
            v-else
            data-type="part"
            :list='partList'
            @delete='delte'
          ></create-mini-table>
          <p class="formErrorMsg">{{ errorMsg.product_menu_part }}</p>
        </div>
      </template>
      <template slot="product_menu_wiki" slot-scope="{ field }">
        <div class="product_menu_box bbx-form-item">
          <div class="normal-title-2">
            <div class="flex-1" :class="{
              'form_is_required': !field.isNull
            }">{{ $t('product.productType.type.productMenuWiki') }}</div>
            <el-button @click="showDialog('wiki')" class="btn_primary">{{ $t('common.base.add2') }}</el-button>
          </div>
          <mini-table
            :id="id"
            v-if="id && !clone"
            ref="wikiTable"
            data-type="wiki"
            @hasValue="hasValue => hasValueChange('product_menu_wiki', hasValue)"
            page-type="edit" />
          <create-mini-table
            v-else
            data-type="wiki"
            :list='wikiList'
            @delete='delte'
          ></create-mini-table>
          <p class="formErrorMsg">{{ errorMsg.product_menu_wiki }}</p>
        </div>
      </template>
      <template slot="productPic"
                slot-scope="{ field }">
        <!-- 对于这种独立的表单项额外增加校验，ref,propField,propValue,validation是必须的 -->
        <form-item
          class="upload-img bbx-form-item"
          ref="productPic"
          :propField="field"
          :propValue="productMenuValue.productPic"
          :validation="extraValidations.productPic"
          :class="{'hide_box':productMenuValue.productPic.length>=5}"
          :label="field.displayName">
          <biz-cropper-upload 
            action="string"
            list-type="picture-card"
            accept="image/png,image/jpg,image/jpeg"
            :on-preview="handlePictureCardPreview"
            :before-upload="onBeforeUploadImage"
            :http-request="UploadImagePic"
            :file-list="productPicList"
            :on-exceed="onExceedPic"
            :on-remove="onRemovePic"
            @cropperDone="picCropperDone"
            multiple
            :limit="5"
            :tips="$t('product.productType.tips.tip12', {px: '750*750', count: '5'})"
            :cropper="{
              autoCropWidth: 750,
              autoCropHeight: 750,
              fixedNumber: [750, 750]
            }"
          ></biz-cropper-upload>
        </form-item>
      </template>
      <template slot="productVideo"
                slot-scope="{ field }">

        <form-item
          ref="productVideo"
          :propField="field"
          :propValue="productMenuValue.productVideo"
          :validation="extraValidations.productVideo"
          :class="['upload-video',productMenuValue.thumbnail.length>=1? 'hide_box': '', 'bbx-form-item']"
          :label="field.displayName"
          style="margin-top:10px;">
          <el-upload class="upload-demo"
                     action="string"
                     accept="video/mp4"
                     :on-preview="handlePreview"
                     :http-request="UploadVideo"
                     :before-upload="onBeforeUploadVideo"
                     :file-list="productVideoList"
                     :on-success="handleSuccess"
                     :on-exceed="onExceedVideo"
                     :on-remove="onRemoveVideo"
                     :disabled='videoDisabled'
                     name="filename"
                     :limit="5">
            <el-button size="mini"
                       class="upload-btn"
                       type="primary" :loading='videoDisabled'>{{videoDisabled?$t('product.productType.btns.btn11'):$t('product.productType.btns.btn12')}}</el-button>
            <div slot="tip" style="margin-bottom:10px;"
                 class="font-12 color-999 mar-t-10">
              {{ $t('product.productType.tips.tip13', { size: '200MB', count: '5' }) }}
            </div>
          </el-upload>
        </form-item>
      </template>
      <template slot="thumbnail"
                slot-scope="{ field }">
        <form-item
          ref="thumbnail"
          :propField="field"
          :propValue="productMenuValue.thumbnail"
          :validation="extraValidations.thumbnail"
          :class="['upload-img',productMenuValue.thumbnail.length>=1? 'hide_box': '', 'bbx-form-item']"
          :label="field.displayName">
          <biz-cropper-upload
            action="string"
            list-type="picture-card"
            accept="image/png,image/jpg,image/jpeg"
            :on-preview="handlePictureCardPreview"
            :before-upload="onBeforeUploadImage"
            :http-request="UploadImageThu"
            :file-list="thumbnailList"
            :on-exceed="onExceedThu"
            :on-remove="onRemoveThu"
            @cropperDone="thuCropperDone"
            :limit="1"
            :tips="$t('product.productType.tips.tip14', { px: '70*70' })"
            :cropper="{
              autoCropWidth: 140,
              autoCropHeight: 140,
              fixedNumber: [70, 70]
            }"
          ></biz-cropper-upload>
        </form-item>
      </template>
      
      <template slot="name" slot-scope="{field}">
        <form-item class="bbx-form-cell-item" :label="field.displayName" :validation="validation.name">
          <form-text :field="field" :value="value.name" @update="update"/>
        </form-item>
      </template>
      
    </form-builder>
    </div>

    <link-dialog ref="linkDialog"
                 @submit="linkSubmit"
                 :part-list='partList'
                 :wiki-list='wikiList'
                 :catalog-tree='catalogTree'
                 :data-type='dataType'
    ></link-dialog>

    <!--start 添加更多字段 -->
    <add-fields-dialog ref="visiableDialog" @onSubmit="onSubmit" :fields="notHiddenFields" :field-ids="fieldIds"></add-fields-dialog>
    <!--end 添加更多字段 -->

    <directory-dialog ref="directoryDialog" :only-add='true' @addSuc='addSuc'></directory-dialog>
    
    <biz-product-type-relation-modify-dialog @success="onBatchModifyProductSuccessHandler" @notModify="submit" :quality-rule-form="qualityRuleForm" :name="backupProductMenuValue.catalogName" ref="BizProductTypeRelationModifyDialog" />
  </div>
</template>

<script>
import {
  getProductMenuField,
  getPageInfo,
  catalogCreate,
  getTreeList,
  cloneData,
  setPageInfo,
  setPagerelationPartOrWiki,
  clonePartOrWiki,
  getProductTypeMaterielBill
} from '@src/api/ProductV2Api';
import Uploader from 'packages/BaseUpload/uploader';
import MiniTable from '@src/modules/productV2/productMenu/WorkTree/compoment/MiniTable.vue';
import CreateMiniTable from './component/CreateMiniTable';
import linkDialog from './component/linkDialog';
import AddFieldsDialog from './WorkTree/compoment/AddMoreFieldsDialog';
import directoryDialog from '../productMenuList/compoment/directoryDialog.vue';

import * as FormUtil from '@src/component/form/util';
import {clickLabel} from '@src/util/function';
import _ from 'lodash'
/* service */
import { unpack, pack, getDefaultQualityStartDate } from '@service/ProductTypeService.ts'
/* enum */
import { ProductTypeFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
/* mixin */
import ProductQualityMixin from '@src/mixins/productQualityMixin'
import VersionMixin from '@src/mixins/versionMixin/index.ts'
/* enum */
/* enum */
import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum'
import BizCropperUpload from '@src/component/business/BizCropperUpload/BizCropperUpload.vue';
import { openAccurateTab } from '@src/util/platform'
import { isDef, useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

let fieldIds_ = [];

export default {
  name:'product-catalog-edit',
  mixins: [ProductQualityMixin, VersionMixin],
  data(){
    let extraValidations = Object.freeze({
      ifRequired: (type) => {
        if (['product_menu_part', 'product_menu_wiki'].includes(type)) {
          let field = this.fields.find(field => field.fieldName === type)
          return !!(field && !field.isNull)
        }

        let isRequired = this.$refs[type]?.showRequired
        if (!isRequired) return false

        return true
      },
      productPic: () => {
        let type = 'productPic'

        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false

        if (!(this.productMenuValue[type]?.length)) {
          return this.$refs[type].errMessage = this.$t('product.productType.tips.tip15')
        }

        return this.$refs[type].errMessage = ''
      },
      productVideo: () => {
        let type = 'productVideo'

        if (!extraValidations.ifRequired(type)) return false

        if (!(this.productMenuValue[type]?.length)) {
          return this.$refs[type].errMessage = this.$t('product.productType.tips.tip16')
        }

        return this.$refs[type].errMessage = ''
      },
      thumbnail: () => {
        let type = 'thumbnail'

        if (!extraValidations.ifRequired(type)) return false

        if (!(this.productMenuValue[type]?.length)) {
          return this.$refs[type].errMessage = this.$t('product.productType.tips.tip17')
        }

        return this.$refs[type].errMessage = ''
      },
      'product_menu_part': () => {
        let type = 'product_menu_part'

        if (!extraValidations.ifRequired(type)) return false
        
        if (this.id && !this.clone) { // 编辑
          if (!this.partHasValue) {
            return this.errorMsg[type] = this.$t('product.productType.tips.tip18')
          }
        } else {
          if (!(this.partList?.length)) { // 新建
            return this.errorMsg[type] = this.$t('product.productType.tips.tip18')
          }
        }

        return this.errorMsg[type] = ''
      },
      'product_menu_wiki': () => {
        let type = 'product_menu_wiki'

        if (!extraValidations.ifRequired(type)) return false

        if (this.id && !this.clone) {
          if (!this.wikiHasValue) {
            return this.errorMsg[type] = this.$t('product.productType.tips.tip19')
          }
        } else {
          if (!(this.wikiList?.length)) {
            return this.errorMsg[type] = this.$t('product.productType.tips.tip19')
          }
        }

        return this.errorMsg[type] = ''
      }
    })
    return{
      fields:[],
      productMenuValue: this.initProductMenuValue(),
      id:'',
      productPicList: [],
      productVideoList: [],
      videoDisabled:false,
      thumbnailList:[],
      pending:false,
      partList:[],
      wikiList:[],
      partHasValue: '',
      wikiHasValue: '',
      dataType:'',
      fieldIds:[],
      catalogTree:[],
      directoryTree:[], // 目录树
      parentIds:[],
      treePath:[],
      clone:false,
      casProps:{
        value:'id',
        label:'name',
        children:'tasks',
        expandTrigger:'hover',
        checkStrictly:true
      },
      backupProductMenuValue: {},
      errorMsg: {
        product_menu_part: '',
        product_menu_wiki: '',
      },
      extraValidations,
      formCellCount:1,
    }
  },
  computed: {
    qualityRuleForm() {
      return this.productMenuValue?.qualityRule || {}
    },
    notHiddenFields() {
      return this.fields.filter(field => !(field.isHidden == 1 || field.isVisible == false))
    },
    titleText() {
      return this.id ? this.$t('product.productType.title.title4') : this.$t('product.productType.title.title5')
    }
  },
  async mounted(){
    try {
      this.id = this.$getUrlObj(window).id || '';
      
      await this.getProductMenuField();
      
      if (this.id) {
        this.getPageInfo();
      } else {
        this.checkNumExceedLimitBeforeHandler && this.checkNumExceedLimitBeforeHandler(
          TenantDataLimitSourceEnum.Product,
          TenantDataLimitTypeEnum.ProductCatalog
        )
        this.getTreeList();
      }
      
      this.cloneData()
      
      clickLabel('cascader-all');
    } catch (error) {
      console.warn(error)
    }
  },
  watch:{
    fieldIds (newVal, oldVal) {
      this.notHiddenFields.map((item) => {
        if (newVal.indexOf(item.id) > -1 || item.isSystem == 1) item['isHidden'] = false;
        else item['isHidden'] = true;
        return item;
      });
      this.$nextTick(()=>{
        this.videoDisabled = false;
      })
    },
  },
  methods:{
    // 获取物料清单
    async fetchMaterialList(id) {
      try {
        let res = await getProductTypeMaterielBill({
          catalogId: this.id || id,
          maxLevel: 2,
          pageNum: 0
        });

        if (!res.success) {
          return this.$platform.notification({
            type: 'error',
            title: res.message,
            message
          });
        }

        let { list } = res.result;
        this.$set(this.productMenuValue, 'productMaterialsBill', list);

      } catch (error) {
        console.warn('获取物料清单fetchMaterialList', error);
      }
    },
    // 返回
    back(){
      window.location.href = `${this.$resourcePrefix}/productV2/catalog/view?id=${this.id}`;
    },
    // 新增目录成功
    addSuc(parentIds){
      this.getTreeList();
      this.catalogInput(parentIds);
    },
    // 新建产品目录
    createDirectory(){
      this.$refs.directoryDialog.open();
    },
    catalogInput(value){
      const length = value.length;
      this.parentIds = value;
      const field = this.fields.find(item=>item.fieldName === 'parentIds');
      this.update({field, newValue:length ? value[length - 1] : ''});
    },
    // 打开添加更多字段弹窗
    showMoreFieldsDialog() {
      this.$refs.visiableDialog.openDialog();
    },
    // 保存添加更多字段
    onSubmit(value) {
      this.fieldIds = value;
    },
    // 获取目录树
    async getTreeList(){
      try{
        const {code, message, result} = await getTreeList({conData:0});
        if(code === 0){
          this.deleteEmpty(result);
          if(this.id){
            if(this.treePath.length > 1){
              this.parentIds = this.treePath.slice(0, -1).map(item=>item.id);
            }
          }
          this.directoryTree = result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.requestError'),
            message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 获取产品类型树
    async cloneData(){
      try{
        const {code, message, result} = await cloneData();
        if(code === 0){
          this.deleteEmpty(result);
          this.catalogTree = result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.requestError'),
            message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list){
      list.forEach(item=>{
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    getPageInfo(id){
      getPageInfo({id:id || this.id}).then(async (res) => {
        if (res.code == 0) {
          res.result.catalogInfo.productVideo = res.result.catalogInfo.productVideo || [];
          res.result.catalogInfo.productPic = res.result.catalogInfo.productPic || [];
          this.thumbnailList = res.result.catalogInfo.thumbnail || [];
          this.productPicList = res.result.catalogInfo.productPic || [];
          this.productVideoList = res.result.catalogInfo.productVideo.filter(item=>item) || [];
          res.result.catalogInfo.productExplain = res.result.catalogInfo.productExplain || [];
          res.result.catalogInfo.thumbnail = res.result.catalogInfo.thumbnail || [];
          // 产品关联物料
          res.result.catalogInfo.productRelateMateriel = [{
            id: res.result.catalogInfo.productRelateMateriel?.materielId || '',
            name: res.result.catalogInfo.productRelateMateriel?.materielName || ''
          }]
            // 处理富文本
          res.result.catalogInfo  = await FormUtil.initRichTextContent(this.fields, res.result.catalogInfo);

          res.result.catalogInfo = { ...res.result.catalogInfo, ...res.result.catalogInfo?.attribute }
          // let form = util.packToForm(this.fields, {}, this.initData.customerAddress);
          this.form = FormUtil.initialize(this.fields, res.result.catalogInfo);
          let catalogInfo = res?.result?.catalogInfo || {}
          this.$set(this, 'productMenuValue', unpack(catalogInfo, this.fields))
          this.backupProductMenuValue = _.cloneDeep(this.productMenuValue)
          this.treePath = res.result.treePath;

          if(this.treePath.length > 1){
            this.parentIds = this.treePath.slice(0, -1).map(item=>item.id);
          }

          if (res.result.selectField) {
            this.$set(this, 'fieldIds', fieldIds_.filter(item => !res.result.selectField.some(ele => ele == item)));
          }

          this.fetchMaterialList(id);
          if(!id) this.getTreeList();
        } else {
          this.$notify.error({
            title: this.$t('common.base.requestError'),
            message: res.message,
            duration: 2000,
          });
        }
      });
    },
    // 删除备件、知识库
    delte(id, dataType) {
      let list = dataType === 'part' ? this.partList : this.wikiList;
      const index = list.findIndex(item=>item.id === id);
      list.splice(index, 1);

      let type = dataType==='part' ? 'product_menu_part' : 'product_menu_wiki'
      if (this.extraValidations.ifRequired(type)) {
        this.extraValidations[type]()
      }
    },
    async linkSubmit(list,value) {
      const dataType = this.dataType;
      const id = value[value.length - 1];
      if(dataType==='copy'){
        const {code, message, result} = await clonePartOrWiki({cloneId:id});
        if(code === 0) {
          this.partList = result.part || [];
          this.wikiList = result.wiki || [];
          this.formFieldValid('product_menu_part')
          this.formFieldValid('product_menu_wiki')
          if(this.id){
            this.clone = true;
          }
        }else{
          this.$notify.error({
            title: this.$t('common.base.requestError'),
            message,
            duration: 2000,
          });
        }
        this.getPageInfo(id);
      }else{
        if(this.id && !this.clone){
          const params = {
            catalogId:this.id,
            relationIds:list.map(item=>item.id),
            type:this.dataType
          }
          this.setPagerelationPartOrWiki(params);
        }else{
          if(dataType === 'part'){
            this.partList = list;
          }else{
            this.wikiList = list;
          }
        }
        let type = dataType==='part' ? 'product_menu_part' : 'product_menu_wiki'
        this.formFieldValid(type)
      }
    },
    // 校验，仅针对产品备件和产品知识库
    formFieldValid (type) {
      if (this.extraValidations.ifRequired(type)) {
        this.extraValidations[type]()
      }
    },
    // 列表是否有值的事件，仅针对产品备件和产品知识库
    hasValueChange (type, hasValue) {
      if (type.includes('part')) {
        this.partHasValue = hasValue
      } else {
        this.wikiHasValue = hasValue
      }
      if (this.extraValidations.ifRequired(type)) {
        this.extraValidations[type]()
      }
    },
    async setPagerelationPartOrWiki(params){
      const {code, message} = await setPagerelationPartOrWiki(params);
      if(code === 0){
        this.$refs[`${this.dataType}Table`].reflash();
      }else{
        this.$notify.error({
          title: this.$t('common.base.requestError'),
          message,
          duration: 2000, 
        });
      }
    },
    showDialog(type){
      this.dataType = type;
      this.$refs.linkDialog.open();
    },
    submit(){
      // 新建且配置自动编号的时候，不传catalogNum
      if(!this.id && this.fields.find(v => v.fieldName === 'catalogNum')?.setting.autoGeneration) {
        delete this.productMenuValue.catalogNum
      }
      this.$refs.form.validate(false).then(valid=>{
        if(valid){
          this.pending = true;
          const parentIds = this.parentIds;
          if(parentIds.length){
            this.productMenuValue.parentId = parentIds[parentIds.length - 1];
          }else{
            this.productMenuValue.parentId = '';
          }
          
          /**
           * !处理时间后发现，自定义字段被赋值到了外层，导致attribute字段没有被处理
           * !这里把attribute字段的值再从外面赋值到里面确保一直
           * !这里不知道后端取自定义字段是从哪里取的，所以这里只能这样处理
           * *可以看看update方法
           */
          const transTimeValue = (formValue) => {
            const newValue = disposeFormSubmitTime(this.fields, formValue) 
            if(newValue.attribute){
              for(const key in newValue.attribute){
                if(isDef(newValue[key])){
                  newValue.attribute[key] = newValue[key]
                }
              }
            }
            return newValue
          }


          if(!this.id){
            this.productMenuValue.partIds = this.partList.map(item=>item.id);
            this.productMenuValue.wikiIds = this.wikiList.map(item=>item.id);
            this.productMenuValue.id = '';
            let { productRelateMateriel = [], productMaterialsBill = [], ...other } = this.productMenuValue;

            let billLists = (productMaterialsBill || []).map(item => {
              return {
                materielId: item.id,
                materielNum: item.num,
                sortId: item.currentSort
              }
            })

            let params = {
              productRelateMateriel: productRelateMateriel[0]?.id,
              productMaterialsBill: billLists,
              ...other
            }
          
            params = this.globalFormSubmissionDataProcessingHandler(this.fields, transTimeValue(params))
            this.checkNumExceedLimitAfterHandler(catalogCreate(pack(params, this.fields)))
            .then(res=>{
              if(res.code === 0){
                let fromId = window.frameElement.getAttribute('fromid')
                this.$platform.refreshTab(fromId)
                this.toDetail(res.result);
              }else{
                this.$platform.notification({
                  type: 'error',
                  title: this.$t('common.base.requestError'),
                  message: res.message
                })
              }
            }).finally(()=>{
              this.pending = false;
            });
            
          }else{
            this.productMenuValue.id = this.id;
            if(this.clone){
              const partIds = this.partList.map(item=>item.id);
              const wikiIds = this.wikiList.map(item=>item.id);
              if(partIds.length || wikiIds.length){
                this.productMenuValue.partIds = partIds;
                this.productMenuValue.wikiIds = wikiIds;
                this.productMenuValue.conData = 1;
              }else{
                this.productMenuValue.conData = 0;
              }
            }else{
              const partTable = this.$refs.partTable;
              const wikiTable = this.$refs.wikiTable;
              if((partTable && partTable.page.list.length) || (wikiTable && wikiTable.page.list.length)){
                this.productMenuValue.conData = 1;
              }else{
                this.productMenuValue.conData = 0;
              }
            }
            
            let { productRelateMateriel = [], productMaterialsBill = [], ...other }= this.productMenuValue;

            let billLists = (productMaterialsBill || []).map(item => {
              return {
                materielId: item.id,
                materielNum: item.num,
                sortId: item.currentSort
              }
            })

            let params = {
              productRelateMateriel: productRelateMateriel[0]?.id,
              productMaterialsBill: billLists,
              ...other
            }

            params = this.globalFormSubmissionDataProcessingHandler(this.fields, transTimeValue(params))
            
            setPageInfo(pack(params, this.fields)).then(res=>{
              if(res.code === 0){
                this.toDetail(this.id);
              }else{
                this.$platform.notification({
                  type: 'error',
                  title: this.$t('common.base.requestError'),
                  message: res.message
                })
              }
            }).finally(()=>{
              this.pending = false;
            });
          }
        }
      });
    },
    toDetail(id){
      let winId = window.frameElement.dataset.id;
      let fromId = window.frameElement.getAttribute('id');

      this.$platform.closeTab(winId);
      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   url: `/productV2/catalog/view?id=${id}`,
      //   reload: true,
      //   close: true,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        reload: true,
        fromId
      })
    },
    onRemoveThu (o, a) {
      this.$set(this.productMenuValue, 'thumbnail', this.productMenuValue.thumbnail.filter(item => item.uid != o.uid));
    },
    onExceedThu () {
      this.$message.error(this.$t('product.productType.tips.tip20', {count: 1}));
    },
    async thuCropperDone(beforeFile, afterFile) {
      const result = await this.handleGetFile({file: beforeFile}, false, afterFile);
      if(result) {
        this.$set(this.productMenuValue, 'thumbnail', [
          ...this.productMenuValue.thumbnail,
          result,
        ]);
      }
    },
    async UploadImageThu (param) {
      const file = await this.handleGetFile(param);
      if(file) {
        this.$set(this.productMenuValue, 'thumbnail', [
          ...this.productMenuValue.thumbnail,
          file,
        ]);
      }
    },
    onRemoveVideo (o, a) {
      this.$set(this.productMenuValue, 'productVideo', this.productMenuValue.productVideo.filter(item => item && item.uid != o.uid));
    },
    onExceedVideo () {
      this.$message.error(this.$t('product.productType.tips.tip21', {count: 5}));
    },
    handleSuccess (_res, _file, fileList) {
      this.videoDisabled = false;
      this.$set(this.productMenuValue, 'productVideo', fileList.map(item => item.response || item));
    },
    onBeforeUploadVideo (file) {
      const isMP4 = file.type === 'video/mp4';
      const isLt50M = file.size / 1024 / 1024 < 200;

      if (!isMP4) {
        this.$message.error(this.$t('product.productType.tips.tip22'));
      }
      if (!isLt50M) {
        this.$message.error(this.$t('product.productType.tips.tip23', {count: '200MB'}));
      }
      // this.fileList.push(file);
      if(isMP4 && isLt50M){
        this.videoDisabled = true;
      }
      return isMP4 && isLt50M;
    },
    UploadVideo (param) {
      return Uploader.upload(param.file, '/files/uploadVideo').then(res => {
        if (res.status == 0) {
          let item_ = {
            uid: param.file.uid,
            id: res.data.id,
            filename: res.data.fileName,
            name: res.data.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: res.data.ossUrl || res.data.url || `/files/get?fileId=${res.data.id}`,
            fileSize: res.data.fileSizeStr,
          }
          return item_
        }
      })
    },
    handlePreview (file) {
      if (file.response?.url) {
        this.$previewVideo(file.response.url);
      }
      if (file.url) {
        this.$previewVideo(file.url)
      }
    },
    onRemovePic (o, a) {
      this.$set(this.productMenuValue, 'productPic', this.productMenuValue.productPic.filter(item => item.uid != o.uid));
    },
    onExceedPic () {
      this.$message.error(this.$t('product.productType.tips.tip20', {count: 5}));
    },
    async picCropperDone(beforeFile, afterFile) {
      const result = await this.handleGetFile({file: beforeFile}, false, afterFile);
      if(result) {
        this.$set(this.productMenuValue, 'productPic', [
          ...this.productMenuValue.productPic,
          result,
        ]);
      }
    },
    async UploadImagePic (param) {
      const file = await this.handleGetFile(param);
      if(file) {
        this.$set(this.productMenuValue, 'productPic', [
          ...this.productMenuValue.productPic,
          file,
        ]);
      }
    },
    onBeforeUploadImage (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error(this.$t('product.productType.tips.tip24'));
      }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2mb!');
      // }
      // this.fileList.push(file);
      return isJPG;
    },
    handlePictureCardPreview (file) {
      this.$previewElementImg(file.url);
      // this.$previewImg(file.url);
    },
    update({ field, newValue, oldValue }){
      let { fieldName, displayName,isSystem } = field;
      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }
      let value = this.productMenuValue;
      if(!value.attribute){
        value.attribute = {}
      }
      if(!isSystem){
        this.$set(value.attribute, fieldName, newValue);
      }
      this.$set(value, fieldName, newValue);
    },
    initProductMenuValue () {
      return {
        catalogName: '',
        productDesc: '',
        productVideo: [],
        productPic: [],
        productExplain: [],
        thumbnail: [],
        attribute: FormUtil.initialize(this.fields, {})?.attribute || {},
        [ProductTypeFieldNameMappingEnum.QualityRule]: {
          // 质保起算时间
          [ProductTypeFieldNameMappingEnum.QualityStartTime]: '',
          // 质保时长
          [ProductTypeFieldNameMappingEnum.QualityTime]: {
            // 质保时长
            qualityTimeNumber: '',
            // 质保时长 (月/年)
            qualityTimeType: ''
          }
        }
      };
    },
    async getProductMenuField(){
      const {code, result, message} = await getProductMenuField();
      if(code === 0){
        if(Array.isArray(result)){
          result.unshift({
            displayName: this.$t('product.productType.type.parentIds'),
            fieldName:'parentIds',
            isSystem:1
          });
        }
        const productExplain = result.find(item=>item.fieldName === 'productExplain');
        if(productExplain) productExplain.accept = '.png,.jpg,.jpeg,.pdf';
        productExplain.tips = this.$t('product.productType.tips.tip25', {
          width: 750,
          size: '200M'
        })
        const fields = result || [];
        const sortedFields = fields
          .sort((a, b) => a.orderId - b.orderId)
          .map((item) => {
            if (item.fieldName == 'catalogName') item['maxlength'] = 500;
            if (item.fieldName == 'catalogNum'){
              item['maxlength'] = 50;
              item.placeholder = this.$t('product.productType.tips.tip26', {count: 50});
            }
            // if (item.fieldName == 'catalogNum') item['disabled'] = true;
            if (item.fieldName == 'productVideo') item['limit'] = 1;
            if(item.formType == 'attachment') item['action'] = '/files/uploadVideo';
            if(item.isSystem === 0){
              if(!this.productMenuValue.attribute) this.productMenuValue.attribute = {};
              this.productMenuValue.attribute[item.fieldName] = null;
            }
            return item;
          });
        fieldIds_ = sortedFields.filter(item => 
          item.isSystem != 1 && !(item.isHidden == 1 || item.isVisible == false)
        ).map((item) => {
          return item.id;
        });
        if(!this.id) this.$set(this, 'fieldIds', _.cloneDeep(fieldIds_))
        this.fields = sortedFields;
        
        this.setDefaultQualityStartDate()
      }else{
        this.$notify.error({
          title: this.$t('common.base.tip.httpIsError'),
          message,
          duration: 2000,
        });
      }
    },
    setDefaultQualityStartDate() {
      try {
        const defaultQualityStartDate = getDefaultQualityStartDate(this.fields)
        this.productMenuValue.qualityRule.qualityStartTime = defaultQualityStartDate
      } catch (error) {
        console.warn(error)
      }
    },
    onBatchModifyProductSuccessHandler() {
      this.submit()
    },

    /**
     * @description: 获取上传文件
     * @param {Object} param el-upload 返回的文件格式
     * @param {Boolean} isNeedUpload 是否需要调用上传接口
     * @param {Object} files isNeedUpload 则需要带上files
     * @return {Object} file
     */    
    async handleGetFile(param, isNeedUpload = true, files) {
      let file = files;
      if(isNeedUpload) {
        const result = await Uploader.upload(param.file, '/files/upload')
        if (result.status != 0) {
          this.$message({
            message: `${result.message}`,
            duration: 1500,
            type: 'error',
          });
          return null;
        }
        file = result.data;
      }
      return !file ? null : {
        uid: param.file.uid,
        id: file.id,
        filename: file.fileName,
        // 如果后端返回url,必须使用。如果后端不返回，需要拼接
        url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
        fileSize: file.fileSizeStr,
      };
    },
  },
  components:{
    MiniTable,
    BizCropperUpload,
    [CreateMiniTable.name]:CreateMiniTable,
    [linkDialog.name]:linkDialog,
    [AddFieldsDialog.name]:AddFieldsDialog,
    [directoryDialog.name]:directoryDialog,
    FormCellChange,
  }
}
</script>

<style lang="scss" scoped>
.product-menu-new {
  min-width: 630px;
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  
  &-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border-bottom: 1px solid #f4f7f5;
    &-left {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #262626;
    }
  }

  &-content {
    flex: 1;
    overflow: auto;
    .form-builder{
      width: 700px;
      margin: 24px auto 10px;
      padding: 0;
    }
  }
}

@mixin title-class {
  height: 48px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  font-weight: 600;
}
.work-tree-data-box {
  .add-product-item{
    margin-bottom: 10px;
    ::v-deep .form-item-control{
      display: flex;
      justify-content: space-between;
       .form-cascader{
          flex:1;
       }
    }
  }
 .el-cascader{
    width: 100%;
  }
  .directory-btn{
    margin-left: 10px;
  }
  .scroll-data {
    overflow-y: scroll;
  }
  .work-data-title {
    padding: 12px;
    font-size: 16px;
    font-weight: 600;
    border-bottom: 1px solid $color-border-l1;
    position: -webkit-sticky;
    position: sticky;
    top: 0;
    z-index: 99;
    background: $bg-color-l2;
  }
  .normal-title-2 {
    @include title-class();
    padding: 0;
    font-weight: 400;
  }
  .normal-title-2-inside {
    @include title-class();
    padding: 0 10px;
  }
  .normal-title-2-bord-bottom {
    @include title-class();
    border-bottom: 1px solid $color-border-l1;
    margin-bottom: 24px;
  }
  .product_menu_first{
     margin-top: 24px;
  }
  .product_menu_box{
    padding: 16px;
    background: $bg-color-l1;
    border-radius: 4px;
    margin-bottom: 24px;
    .normal-title-2 {
      height: 32px;
      margin-bottom: 16px;

    }
  }
  .btn_primary{
    color:$color-primary;;
    border-color: #b8eded;
    background-color: $color-primary-light-1;
  }
}

.formErrorMsg {
  color: #f56c6c;
  font-size: 12px;
  height: 22px;
  line-height: 22px;
  margin: 3px 0 0;
}
.form_is_required:after {
  content: '*' !important;
  color: #f00 !important;
  margin-left: 4px;
}
</style>
<style lang="scss">
.theme-default {
  padding: 12px;
}
.el-radio{
  margin-bottom: 0;
}
.upload-img {
  .el-upload-list__item {
    transition: none !important;
  }
  margin-bottom: 12px;
  .el-upload-list__item label {
    padding: 0;
  }
  .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
    margin-bottom: 6px;
    &:hover {
      border-color: $color-primary;
    }
  }
  .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}

.upload-video {
  label {
    padding: 0 !important;
  }
  .el-upload-list__item {
    transition: none !important;
  }
  .upload-btn {
    padding: 7px 12px;
    font-size: 12px;
    border-radius: 4px;
  }
}
.el-checkbox {
  margin-bottom: 15px;
}

.el-cascader-menu__wrap .el-checkbox {
  margin-bottom: 0;
}

.form-item label {
  padding: 4px 0 0 0;
}

.table-footer {
  padding: 0;
  background: none;
}

.hide_box .el-upload--picture-card {
  display: none;
}
</style>
